<template>
  <div class="login-way">
    <el-form ref="registerForm"
             :model="registerForm"
             status-icon
             :rules="registerRules">

      <el-form-item prop="mobile">
        <el-input v-model="registerForm.mobile"
                  placeholder="请输入手机号"
                  oninput = "value=value.replace(/[^\d]/g,'')"
                  maxlength="11"
                  autocomplete="off"
                  style="width: 50%;float: left"/>
        <el-button
                type="danger"
                class="sms-btn"
                :disabled="disabled=!show"
                autocomplete="off"
                :loading="loading"
                @click="sendSms">
          <span v-show="show">获取验证码</span>
          <span v-show="!show" class="count">{{ count + `秒可再次获取`}}</span>
        </el-button>
      </el-form-item>

      <el-form-item class="password-item" prop="code">
        <el-input
                v-model="registerForm.code"
                oninput = "value=value.replace(/[^\d]/g,'')"
                placeholder="请输入验证码"
                maxlength="6"/>
      </el-form-item>

      <el-form-item class="password-item" prop="password" style="padding-top: 8px">
        <el-input v-model="registerForm.password"
                  placeholder="请输入密码"
                  maxlength="20"
                  autocomplete="off"
                  show-password/>
      </el-form-item>

      <el-form-item class="password-item" prop="check" style="padding-top: 8px">
        <el-input v-model="registerForm.check"
                  maxlength="20"
                  placeholder="请再次输入密码"
                  show-password
                  autocomplete="off"/>
      </el-form-item>

      <el-form-item class="password-item" prop="email" style="padding-top: 8px">
        <el-input
                v-model="registerForm.email"
                placeholder="请输入邮箱"
                autocomplete="off"
                maxlength="30"/>
      </el-form-item>

      <el-form-item class="auto-login-item" style="padding-top: 8px">
        <el-checkbox v-model="registerForm.argement">
          同意
        </el-checkbox>
        <span class="agreement">《慕课网注册协议》</span>
      </el-form-item>
    </el-form>
    <div class="login-btn" @click="handleRegisterClick">
      注册
    </div>
  </div>
</template>
<script>
import { mapMutations } from 'vuex'
import { checkMobile, register, getSms, checkCode} from '@/api/user';
import { validMobile, validPassword, validCode, validEmail} from '@/validate/register';

const TIME_COUNT = 60; //更改倒计时时间


export default {
  inject:['reload'],
  data () {
    //检验手机号
    const validateMobile = (rule, value, callback) => {
      if (!validMobile(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        checkMobile(value).then(result => {
          let {code} = result
          if (code ===20000) callback();
          else callback(new Error("该手机号已注册，请登录"));
        })
      }
    }

    //检验验证码
    const validateCode = (rule, value, callback) => {
      if (!validCode(value)){
        callback(new Error("请输入正确的验证码"));
      }
      else {
        checkCode(this.registerForm.mobile,value).then(result => {
          let {code,message} = result
          if (code === 20000) callback()
          else callback(new Error(message))
        })
      }
    }

    //检验密码
    const validatePassword = (rule, value, callback) => {
      if (!validPassword(value)){
        callback(new Error("请输入正确的密码，密码格式为6-20位的字母与数字组合"));
      }
      else callback()
    }

    //检验确认密码
    const validateCheck = (rule, value, callback) => {
      if (value !== this.registerForm.password || value.length < 6){
        callback(new Error("两次密码输入不一致，请重新输入"))
      }
      else callback()
    }

    //检验邮箱
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)){
        callback(new Error("请输入正确的邮箱"))
      }
      else callback()
    }

    return {
      show: true,  // 初始启用按钮
      count: '',   // 初始化次数
      timer: null,
      loading: false,
      registerForm: {
        mobile: '',
        password: '',
        code: '',
        email: '',
        check: '',
        argement: true
      },
      //检验规则
      registerRules:{
        mobile:[{validator: validateMobile,trigger: 'blur'}],
        code:[{validator: validateCode,trigger: 'blur'}],
        password:[{validator: validatePassword,trigger: 'blur'}],
        check:[{validator: validateCheck,trigger: 'blur'}],
        email:[{validator: validateEmail,trigger: 'blur'}],
      },
    }
  },
  methods: {
    // 注册点击事件
    handleRegisterClick () {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          //所有检验通过，发送注册请求
          register(this.$qs.stringify(this.registerForm)).then(result => {
            let {code} = result
            if (code === 20000){
              // 关闭弹窗
              this.setShowLogin(false)
              // 重载页面
              this.reload()
              this.$message.success('注册成功！请登录！');
            }
            else {
              this.$message.error("注册失败！请正确填写注册信息！")
            }
          })
        } else {
          //不通过
          return false;
        }
      });
    },

    sendSms(){
      // 手机号输入正确才能发送验证码
      if (!validMobile(this.registerForm.mobile)) {
        this.$message.error("请输入正确的手机号码")
        return;
      } else {
        this.loading = true
        checkMobile(this.registerForm.mobile).then(result => {
          let {code} = result
          if (code === 20000){
            //发送验证码
            let data = {mobile: this.registerForm.mobile}
            getSms(this.$qs.stringify(data)).then(result => {
              let {code} = result
              if (code === 20000){
                this.loading = false
                this.$message.success("验证码发送成功！")
                //计时器
                if (!this.timer) {
                  this.count = TIME_COUNT;
                  this.show = false;
                  this.timer = setInterval(() => {
                    if (this.count > 0 && this.count <= TIME_COUNT) {
                      this.count--;
                    } else {
                      this.show = true;
                      clearInterval(this.timer);  // 清除定时器
                      this.timer = null;
                    }
                  }, 1000)
                }
              }

              else {
                this.loading = false
                this.$message.error("验证码发送错误！")
              }
            })
          }
          else {
            this.$message.error("该手机号已注册，请登录")
          }
        })
      }
    },

    // vuex
    ...mapMutations('login', {
      'setUserInfo': 'SET_USER_INFO',
      'setShowLogin': 'SET_SHOW_LOGIN'
    })
  }
}
</script>
<style lang="stylus" scoped>
  @import '~assets/stylus/login-form.styl';

  .login-way
    .agreement
      color: #37f;
      cursor: pointer;
    >>> .el-checkbox__label
      color: #9199a1!important;
  .sms-btn
    float: right;
    width 141.57px
    background-color: #f20d0d;
    height: 48px;
    font-size 14px
</style>
